﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.SystemModule;
using EasyXaf.LowCode.RulesEngineEditors.Models;

namespace EasyXaf.LowCode.RulesEngineEditors;

public class ActionObjectViewController : ObjectViewController<ObjectView, ActionObject>
{
    private NewObjectViewController _newObjectViewController;
    private DeleteObjectsViewController _deleteObjectsViewController;

    public WorkflowObject Workflow { get; set; }

    protected override void OnActivated()
    {
        base.OnActivated();

        _newObjectViewController = Frame.GetController<NewObjectViewController>();
        if (_newObjectViewController != null)
        {
            _newObjectViewController.ObjectCreated += NewObjectViewController_ObjectCreated;
        }

        _deleteObjectsViewController = Frame.GetController<DeleteObjectsViewController>();
        if (_deleteObjectsViewController != null)
        {
            _deleteObjectsViewController?.DeleteAction.Active.RemoveItem("IsPersistent");
            _deleteObjectsViewController.DeleteAction.Changed += DeleteAction_Changed;
        }
    }

    protected override void OnDeactivated()
    {
        if (_newObjectViewController != null)
        {
            _newObjectViewController.ObjectCreated -= NewObjectViewController_ObjectCreated;
        }

        _deleteObjectsViewController = Frame.GetController<DeleteObjectsViewController>();
        if (_deleteObjectsViewController != null)
        {
            _deleteObjectsViewController.DeleteAction.Changed -= DeleteAction_Changed;
        }

        base.OnDeactivated();
    }

    private void NewObjectViewController_ObjectCreated(object sender, ObjectCreatedEventArgs e)
    {
        if (e.CreatedObject is OutputExpressionActionObject outputExpressionActionObject)
        {
            outputExpressionActionObject.Workflow = Workflow;
        }
    }

    private void DeleteAction_Changed(object sender, ActionChangedEventArgs e)
    {
        if (sender is SimpleAction action)
        {
            action.Active.RemoveItem("IsPersistent");
        }
    }
}
